package com.hub.downloadbrowsing

import com.hub.videobrowsdownload.BrowsApplication
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.net.HttpURLConnection
import java.net.URL
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.security.brows.room.BrowsRoomHelper
import com.security.brows.room.BrowsWebFavoriteBean

class AppApplication : BrowsApplication() {

    override fun onCreate() {
        super.onCreate()

        browsMyViewModel.isDarkTheme.value = true

        CoroutineScope(Dispatchers.IO).launch {
            try {// JSON 接口 URL
                val url = "https://gitee.com/afra55/public-tree/raw/master/favorite.json"

                // 创建 URL 对象
                val apiUrl = URL(url)

                // 打开连接
                val connection = apiUrl.openConnection() as HttpURLConnection

                // 设置请求方式
                connection.requestMethod = "GET"

                // 获取响应代码
                val responseCode = connection.responseCode

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 读取响应
                    val inputStream = connection.inputStream
                    val reader = inputStream.bufferedReader()
                    val response = StringBuilder()
                    var line: String?

                    while (reader.readLine().also { line = it } != null) {
                        response.append(line)
                    }

                    // 关闭连接
                    reader.close()
                    connection.disconnect()

                    // 将结果输出为字符串
                    val jsonResponse = response.toString()
                    val ja = JSON.parseArray(jsonResponse)
                    val time = System.currentTimeMillis()
                    for (i in ja.indices) {
                        val jb = ja.getJSONObject(i)
                        val name = jb.getString("name")
                        val webUrl = jb.getString("url")
                        val icon = jb.getString("icon")
                        val sort = jb.getIntValue("sort")
                        BrowsWebFavoriteBean.save(this@AppApplication, time + sort, webUrl, null, name, icon)
                    }
                } else {
                    println("Error: $responseCode")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}